package ru.yelbota.flex.as3jobs.libs {

import flash.events.Event;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;
import flash.utils.ByteArray;

import ru.yelbota.flex.as3jobs.Job;
import ru.yelbota.flex.as3jobs.as3_jobs;
import ru.yelbota.flex.as3jobs.exceptions.JobWaitEventException;

use namespace as3_jobs;

public class JobUrlLoader {

    private static function load(loaderFactory:Function, request:URLRequest):* {

        Job.incrementCallIndex();

        var loader:URLLoader = Job.getResource(Job.getCurrentJob(), request.url) as URLLoader;

        if (loader == null) {
            loader = loaderFactory();
            throw new JobWaitEventException(Event.COMPLETE, loader, request.url);
        }
        else {
            return loader.data;
        }

    }

    public static function loadBytes(request:URLRequest):ByteArray {
        function loaderFactory():URLLoader {
            const loader:URLLoader = new URLLoader(request);
            loader.dataFormat = URLLoaderDataFormat.BINARY;
            return loader;
        }
        return load(loaderFactory, request) as ByteArray;
    }

    public static function loadText(request:URLRequest):String {
        function loaderFactory():URLLoader {
            const loader:URLLoader = new URLLoader(request);
            loader.dataFormat = URLLoaderDataFormat.TEXT;
            return loader;
        }
        return load(loaderFactory, request) as String;
    }

    public static function loadVariables(request:URLRequest):Object {
        function loaderFactory():URLLoader {
            const loader:URLLoader = new URLLoader(request);
            loader.dataFormat = URLLoaderDataFormat.VARIABLES;
            return loader;
        }
        return load(loaderFactory, request);
    }
}

}

